package com.nl.controller.web.service;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.nl.controller.common.annotation.SystemServiceLog;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.service.CommonService;
import com.nl.controller.common.util.DateUtils;
import com.nl.controller.web.bean.SmsBaseStation;
import com.nl.controller.web.bean.SmsReportDetail;
import com.nl.controller.web.bean.SmsReportTotal;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.mapper.SmsBaseStationMapper;
import com.nl.controller.web.mapper.SmsReportDetailMapper;
import com.nl.controller.web.mapper.SmsReportTotalMapper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class SmsReportDetailService {
	@Autowired
	private SmsReportTotalMapper smsReportTotalMapper;
    @Autowired
    private SmsReportDetailMapper smsReportDetailMapper;

    @Autowired
    private CommonService commonService;
    
    @Autowired
    private SmsBaseStationMapper smsBaseStationMapper;
    

    @SystemServiceLog(description = "短信发送明细查询", value = false)
    public PageInfo<SmsReportDetail> findSmsInfo
            (int page, int limit, String cityId, String way, String month, String startTime, String endTime, String mgrId, String receiver,String mgrName,String regionId, String stationId, String countyId) {
        Map<String, Object> map = new HashMap<>();
        List<SmsReportDetail> list = new ArrayList();
        if(stationId!=null&&!"".equals(stationId)){
        		regionId="";
        }
        //按时间段查询
        map.put("mgrId", mgrId);
        map.put("regionId", regionId);
        map.put("stationId", stationId);
        map.put("cityId", cityId);
        map.put("countyId", countyId);
        map.put("receiver", receiver);
        PageInfo<SmsReportDetail> pageInfo = null;
        try {
            if ("0".equals(way)) {
            	
            	PageHelper.startPage(page, limit);
                map.put("startTime", startTime);
                map.put("endTime", endTime);
                list = smsReportDetailMapper.findSmsReportDetailDay(map);
                list = dimPhoneNum(list);
                list = this.SetCountyName(list,regionId);
                //PageHelper.startPage(page, limit);
                //list=this.startPage(list, page, limit);
                
                pageInfo = new PageInfo<>(list);
                

                //按照月份查询
            } else if ("1".equals(way)) {
            	PageHelper.startPage(page, limit);
                map.put("month", month);
                map.put("startTime", month + "01");
                map.put("endTime", DateUtils.getLastDayOfMonth(month));
                map.put("startPage", (page - 1) * limit);
                map.put("endPage", (page) * limit);

                list = smsReportDetailMapper.findSmsReportDetailMonth(map);
                list = dimPhoneNum(list);
                list = this.SetCountyName(list,regionId);
                pageInfo = new PageInfo<>(list);
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("短信发送明细查询出现异常：");
            throw e;
        }

        try {
        } catch (Exception e) {
            log.error("短信发送明细查询失败");
            throw new SmsException("短信发送明细查询失败");
        }
        return pageInfo;
    }


    @SystemServiceLog(description = "查询项目下的区域", value = false)
    public List<SmsReportDetail> findRegionInfo(String mgrId, String cityId) {
        Map<String, Object> map = new HashMap<>();
        map.put("mgrId", mgrId);
        map.put("cityId", cityId);
        String regionId="";
        List<SmsReportDetail> list = new ArrayList<>();
        try {
            list = smsReportDetailMapper.findRegionInfo(map);
            list = dimPhoneNum(list);
            list = this.SetCountyName(list,regionId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询项目下的区域异常：", mgrId);
        }
        return list;
    }

    @SystemServiceLog(description = "查询区域下的基站", value = false)
    public List<SmsReportDetail> findStationInfo(String regionId, String cityId, String mgrId) {
        Map<String, Object> map = new HashMap<>();
        map.put("regionId", regionId);
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        log.info(mgrId);
        List<SmsReportDetail> list = new ArrayList<>();
        try {
            list = smsReportDetailMapper.findStationInfo(map);
//            list = dimPhoneNum(list);
//            list = this.SetCountyName(list);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("查询区域下的基站：", regionId);
        }
        return list;
    }


    /**
     * 普通下载方式获取数据表中的数据，导出
     *
     * @param way
     * @param month
     * @param startTime
     * @param endTime
     * @param mgrId
     * @param regionId
     * @param stationId
     * @return
     */

    public JSONArray download(String way, String month, String startTime, String endTime, String mgrId, String regionId, String stationId,String cityId,String countyId) {
        Map<String, Object> map = new HashMap<>();
        JSONArray jsonArray;
        //按时间段方式查询
        if ("0".equals(way)) {
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            //按月方式查询
        } else if ("1".equals(way)) {
            map.put("startTime", month + "01");
            map.put("endTime", DateUtils.getLastDayOfMonth(month));
        }
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        map.put("regionId", regionId);
        map.put("stationId", stationId);
        map.put("countyId", countyId);
        try {
            jsonArray = smsReportDetailMapper.downLoad(map);
            List<SmsReportDetail> list = JSONObject.parseArray(jsonArray.toJSONString(), SmsReportDetail.class);
            //list = this.SetCountyNameWithMgrId(list,mgrId);
            list=this.SetCountyName(list,regionId);
            for(int i=0;i<list.size();i++){
            	if("2000250".equals(list.get(i).getUserPlace())){
            		list.get(i).setUserPlace("江苏省");
            	}else{
            		list.get(i).setUserPlace("非江苏省");
            	}
            	String countyName = list.get(i).getCountyName();
            	if(!"".equals(countyName) && null != countyName){
            		String belong = list.get(i).getCityName()+"/"+countyName;
            		list.get(i).setCountyName(belong);
            	}else{
            		list.get(i).setCountyName(list.get(i).getCityName());
            	}
            }
            list = dimPhoneNum(list);
            
            jsonArray= JSONArray.parseArray(JSON.toJSONString(list));
            
            if(!"".equals(mgrId)&&null!=mgrId){
            	commonService.createSmsOperLog("7", mgrId,"导出发送明细报表："+mgrId, "0", "22");
            }else{
            	commonService.createSmsOperLog("7", "0","导出发送明细报表", "0", "22");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(!"".equals(mgrId)&&null!=mgrId){
            	commonService.createSmsOperLog("7", mgrId,"导出发送明细报表："+mgrId, "1", "22");
            }else{
            	commonService.createSmsOperLog("7", "0","导出发送明细报表", "1", "22");
            }
            
            log.error("短信发送明细导出失败");
            throw new SmsException("短信发送明细查询失败");
        }
        return jsonArray;
    }

    public List<SmsReportDetail> download2(String way, String month, String startTime, String endTime, String mgrId, String regionId, String stationId,String cityId,String countyId) {
        Map<String, Object> map = new HashMap<>();
        JSONArray jsonArray;
        List<SmsReportDetail> list = new ArrayList<>();
        //按时间段方式查询
        if ("0".equals(way)) {
            map.put("startTime", startTime);
            map.put("endTime", endTime);
            //按月方式查询
        } else if ("1".equals(way)) {
            map.put("startTime", month + "01");
            map.put("endTime", DateUtils.getLastDayOfMonth(month));
        }
        map.put("cityId", cityId);
        map.put("mgrId", mgrId);
        map.put("regionId", regionId);
        map.put("stationId", stationId);
        map.put("countyId", countyId);
        try {
            jsonArray = smsReportDetailMapper.downLoad(map);
            list = JSONObject.parseArray(jsonArray.toJSONString(), SmsReportDetail.class);
            //list = this.SetCountyNameWithMgrId(list,mgrId);
            list=this.SetCountyName(list,regionId);
            for(int i=0;i<list.size();i++){
                if("2000250".equals(list.get(i).getUserPlace())){
                    list.get(i).setUserPlace("江苏省");
                }else{
                    list.get(i).setUserPlace("非江苏省");
                }
                String countyName = list.get(i).getCountyName();
                if(!"".equals(countyName) && null != countyName){
                    String belong = list.get(i).getCityName()+"/"+countyName;
                    list.get(i).setCountyName(belong);
                }else{
                    list.get(i).setCountyName(list.get(i).getCityName());
                }
            }
            list = dimPhoneNum(list);

            jsonArray= JSONArray.parseArray(JSON.toJSONString(list));

            if(!"".equals(mgrId)&&null!=mgrId){
                commonService.createSmsOperLog("7", mgrId,"导出发送明细报表："+mgrId, "0", "22");
            }else{
                commonService.createSmsOperLog("7", "0","导出发送明细报表", "0", "22");
            }
        } catch (Exception e) {
            e.printStackTrace();
            if(!"".equals(mgrId)&&null!=mgrId){
                commonService.createSmsOperLog("7", mgrId,"导出发送明细报表："+mgrId, "1", "22");
            }else{
                commonService.createSmsOperLog("7", "0","导出发送明细报表", "1", "22");
            }

            log.error("短信发送明细导出失败");
            throw new SmsException("短信发送明细查询失败");
        }
        return list;
    }


    @SystemServiceLog(description = "短信发送明细文件下载", value = false)
    public List<File> fileDownload
    (String cityId, String way, String month, String startTime, String endTime, String mgrId) {
        List<File> files = new ArrayList();
        //按月导出
        if ("1".equals(way)) {
            for (String day : this.list(month)) {
                try {
                    files.add(this.getFile(cityId, mgrId, day));
                } catch (Exception e) {
                    e.printStackTrace();
                    log.error("文件不存在");
                }
            }
        } else {
            try {
                for (String day : this.list(startTime, endTime)) {
                    files.add(this.getFile(cityId, mgrId, day));
                }
            }catch (Exception e) {
                e.printStackTrace();
                log.error("文件不存在");
            }
        }
        if(!"".equals(mgrId)&&null!=mgrId){
        	commonService.createSmsOperLog("7", mgrId,"导出发送明细报表："+mgrId, "0", "22");
        }else{
        	commonService.createSmsOperLog("7", "0","导出发送明细报表", "0", "22");
        }
        return files;
    }



    public File getFile(String cityId, String mgrId, String day) {
        File file = null;
        StringBuffer fileName = new StringBuffer();
        fileName.append(GlobalConst.PATH);
        fileName.append(cityId);
        fileName.append("/");
        fileName.append(mgrId);
        fileName.append("/");
        fileName.append(mgrId);
        fileName.append(day);
        fileName.append(".xlsx");
        try {
            log.info(fileName.toString());
            file = new File(fileName.toString());
        } catch (Exception e) {
            log.error(fileName.toString() + "文件不存在");
        }
        return file;
    }

    /**
     * 转换时间的格式
     *
     * @param date
     * @return
     */
    private int forMatDate(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        SimpleDateFormat formatter2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int result = 0;
        try {
            Date time = formatter2.parse(date);
            String temp = formatter.format(time);
            result = Integer.parseInt(temp);
        } catch (ParseException e) {
            e.printStackTrace();
            log.error("时间转换出错");
        }
        return result;
    }

    /**
     * 一个月内所日期的数组
     */
    private List<String> list(String yearMonth) {
        List<String> list = new ArrayList<>();
        int days = DateUtils.getDayOfMonth(yearMonth);
        for (int i = 1; i <= days; i++) {
            if (i < 10) {
                String day = yearMonth + "0" + i;
                list.add(day);
            } else {
                String day = yearMonth + i;
                list.add(day);
            }
        }
        return list;
    }

    /**
     * 时间段内的时间
     *
     * @param
     * @return
     */
    private List<String> list(String startTime, String endTime) {
        int start = this.forMatDate(startTime);
        int end = this.forMatDate(endTime);
        int result = end - start;
        List<String> list = new ArrayList<>();
        for (int i = 0; i <= result; i++) {
            list.add(String.valueOf(start + i));
        }
        return list;
    }
    /**
     * 模糊手机号码
     * @param list
     * @return
     */
    private List<SmsReportDetail>  dimPhoneNum(List<SmsReportDetail> list) {
        String str = "****";
        StringBuilder sb;
        try {
            for (SmsReportDetail smsReportDetail : list) {
                String msisdn = smsReportDetail.getMsisdn();
                if (msisdn!= null) {
                    sb= new StringBuilder(msisdn);
                    sb.replace(3, 7, str);
                    msisdn = sb.toString();
                    smsReportDetail.setMsisdn(msisdn);
                }
            }
        } catch (Exception e) {
            log.error("解密失败");
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 获取基站名称和区县名称
     * @param list
     * @return
     */
    private List<SmsReportDetail> SetCountyName(List<SmsReportDetail> list,String regionId){
    	HashMap<String, SmsBaseStation> hashMap = new HashMap<String, SmsBaseStation>();
    	HashMap<String, Object> param = new HashMap<String, Object>();
    	List<SmsReportDetail> newReportList=new ArrayList<SmsReportDetail>();
    	List<SmsBaseStation> baseStationList;
    	SmsBaseStation smsBaseStation=new SmsBaseStation();
    	int count1 = 0;
    	int count2 = 0;
    	//System.err.println("------list长度："+list.size());
    	if (!list.isEmpty()) {
			for (SmsReportDetail smsReportDetail : list) {
				String countyId = smsReportDetail.getCountyId();
				if (null != countyId && !"".equals(countyId))  {
					String countyName = smsReportTotalMapper.getCountyName(countyId);
					smsReportDetail.setCountyName(countyName);
				}
				String mgrId =  smsReportDetail.getMgrId();
				String stationId = smsReportDetail.getStationId();
				
				if (stationId!=null && !"".equals(stationId)) {
					if (hashMap.containsKey(mgrId+stationId)) {
						smsBaseStation = hashMap.get(mgrId+stationId);
						count2++;
					}else {
						param.put("mgrId", mgrId);
						param.put("stationId",stationId);
						baseStationList = smsBaseStationMapper.findSmsBaseStation(param);
						if(baseStationList.size()!=0){
							smsBaseStation=baseStationList.get(0);
							count1++;
							hashMap.put(mgrId+stationId, smsBaseStation); 
						}else{
							smsBaseStation.setStationName("暂无数据");
							smsBaseStation.setRegionId("暂无数据");
							smsBaseStation.setRegionName("暂无数据");
						}; 
					}
					smsReportDetail.setStationName(smsBaseStation.getStationName());
					smsReportDetail.setRegionId(smsBaseStation.getRegionId());
					smsReportDetail.setRegionName(smsBaseStation.getRegionName()); 
					
				}
			}
		}
    	hashMap.clear();
    	log.info("查询数据库"+count1);
    	log.info("查询内存"+count2);
    		return list;
    }
    
    private List<SmsReportDetail> SetStationInfo(List<SmsReportDetail> list){
    	HashMap<String, Object> param = new HashMap<String, Object>();
    	List<SmsBaseStation> baseStationList;
    	SmsBaseStation smsBaseStation=new SmsBaseStation();
    	if(list!=null){
    		for(SmsReportDetail smsReportDetail : list){
    			String mgrId =  smsReportDetail.getMgrId();
				String stationId = smsReportDetail.getStationId();
				if (stationId!=null && !"".equals(stationId)) {
						param.put("mgrId", mgrId);
						param.put("stationId",stationId);
						baseStationList = smsBaseStationMapper.findSmsBaseStation(param);
						if(baseStationList.size()!=0){
							smsBaseStation=baseStationList.get(0);
						}else{
							smsBaseStation.setStationName("暂无数据");
							smsBaseStation.setRegionId("暂无数据");
							smsBaseStation.setRegionName("暂无数据");
						}; 					
						smsReportDetail.setStationName(smsBaseStation.getStationName());
						smsReportDetail.setRegionId(smsBaseStation.getRegionId());
						smsReportDetail.setRegionName(smsBaseStation.getRegionName()); 
				}
    		}
    	}
    	return list;
    }
    
    
    public List<SmsReportDetail>  startPage(List<SmsReportDetail>  list, Integer pageNum,Integer pageSize) {
        if (list == null) {
            return null;
        }
        if (list.size() == 0) {
            return null;
        }

        Integer count = list.size(); // 记录总数
        Integer pageCount = 0; // 页数
        if (count % pageSize == 0) {
            pageCount = count / pageSize;
        } else {
            pageCount = count / pageSize + 1;
        }

        int fromIndex = 0; // 开始索引
        int toIndex = 0; // 结束索引

        if (pageNum != pageCount) {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = fromIndex + pageSize;
        } else {
            fromIndex = (pageNum - 1) * pageSize;
            toIndex = count;
        }

        List<SmsReportDetail>  pageList = list.subList(fromIndex, toIndex);

        return pageList;
    }
}
